import React from 'react';
import { Cascader,Input,Button,Result } from 'antd';
import {options} from "../../../assets/js/country_level3_data";
import './index.less'
import {connect} from "react-redux";
import {nanoid} from "nanoid";
import {confirmOrder} from "../../../network/order";
import Notice from "../../../components/Notice";
import {clearMyCar} from "../../../redux/actions/shopCar";
import {withRouter} from "react-router-dom";

function Confirm(props){
    const [userId] = React.useState(`${sessionStorage.getItem('userId')}`)
    const [usernickname] = React.useState(`${sessionStorage.getItem('userNickName')}`);
    const [useremail] = React.useState(`${sessionStorage.getItem('userEmail')}`)
    const [addr1,setaddr1] = React.useState('');
    const [addr2,setaddr2] = React.useState('');
    const [isloading,setLoading] = React.useState(false)
    function getAddr1(value){
        setaddr1(value)
    }
    function getAddr2(e){
        setaddr2(e.target.value)
    }
    async function submit(){
        setLoading(true)
        //验证用户是否登录，并且是否选择并填写了地址，并且购物车不为空才能提交订单
        if(userId && addr1 && addr2 && props.carList.length !== 0){
            let orderInfo = {
                orid: nanoid(),//随机生成订单号
                userId,
                useremail,
                usernickname,
                totalprice:getAllPrice(),
                addr: `${addr1},${addr2}`,
                goodsList: JSON.stringify(props.carList)
            }
            let result = await confirmOrder(orderInfo)
            if(result.code === 200){
                //提交订单并清空当前购物车
                props.clearMyCar(userId)
                Notice('success','提交订单成功')
            }else{
                Notice('error','提交订单失败')
            }
        }else{
            Notice('warning','订单信息错误','提交信息不正确')
        }
        setTimeout(() => {
            setLoading(false)
        },500)
    }
    function getAllPrice(){
        let price = 0;
        props.carList.forEach(item => {
            price += item.gcount * item.gprice
        })
        return price.toFixed(2)
    }
    return (
        userId && props.carList.length !== 0 ? (<div className='orderConfirm'>
            <h1>
                订单确认
            </h1>
            <div className='orderUser'>
                <h2>下单用户</h2>
                <span>{usernickname}</span>
            </div>
            <div className='orderEmail'>
                <h2>收货人邮箱</h2>
                <span>{useremail}</span>
            </div>
            <div className='addr'>
                <h2>收件人地址</h2>
                <Input.Group compact={true} className='addrInput'>
                    <Cascader size="large" options={options} onChange={getAddr1} className='cas' placeholder='省/市/区'/>
                    <Input placeholder='详细地址' className='addDetail' onInput={getAddr2}/>
                </Input.Group>
            </div>
            <div className='totalPrice'>
                <div className='moneyDesc'>
                    <div><span>商品总金额</span><span>￥{getAllPrice()}</span></div>
                    <div><span>运费</span><span>￥0(包邮)</span></div>
                </div>
                <div className='moneyCount'>
                    <div><span>总计</span><span>￥{getAllPrice()}</span></div>
                </div>
                <Button loading={isloading} className='submitOrder' onClick={submit}>提交订单</Button>
            </div>
        </div>) : (
            <div className='warningOrder' style={{paddingTop: '40px'}}>
                <Result
                    status="warning"
                    title="您还未登录或购物车为空,无法确认下单"
                    extra={
                        <Button type="primary" key="console" onClick={() => props.history.push('/mall/home')}>
                            去购物
                        </Button>
                    }
                />
            </div>
        )
    )
}

export default withRouter(connect(
    state => ({carList: state.carList}),
    {clearMyCar}
)(Confirm));